package com.virtium.vpm.controller;

import java.util.ArrayList;
import java.util.ListIterator;

import com.virtium.vpm.dao.DAOFactory;
import com.virtium.vpm.dao.UserDAO;
import com.virtium.vpm.hibernate.model.MajorTask;
import com.virtium.vpm.hibernate.model.User;
import com.virtium.vpm.json.JSONArray;

public class UserManager {
	public static ArrayList<User> arrUser = null;
	public static User getUserByID(int id){
		try{
			if(arrUser == null) getAllUser();
			ListIterator lt = arrUser.listIterator();
			while(lt.hasNext()){
				User user = (User)lt.next();
				if(user.getId().equals(id)) return user;
			}
		}catch(Exception ex){}
		return null;
	}
	public static ArrayList<User> getAllUser(){
		if(arrUser != null) return arrUser;
		try{			
			arrUser = new ArrayList<User>();
			UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
			arrUser.addAll(userDAO.findAll());
			arrUser = removeAdminUser(arrUser);
			return arrUser;
		}catch(Exception ex){}
		return null;
	}
	
	public static String getAllStringUser(){
		try{
			if(arrUser == null) getAllUser();
			JSONArray jsonArray = new JSONArray();
			ListIterator lt = arrUser.listIterator();
			while(lt.hasNext()){
				User user = (User)lt.next();
				if(user.getUserName().equals("admin")) continue;
				
				jsonArray.put(user.getFullName());
			}
			return jsonArray.toString();
		}catch(Exception ex){}
		return null;
	}

	public void delete(User user){
		try{
			MajorTaskManager mtm = new MajorTaskManager();
			ArrayList<MajorTask> arrMajorTask = mtm.getListMajorTaskByUserID(user.getId());
			for(int i = 0; i < arrMajorTask.size();i++)
				mtm.deleteMajorTask(arrMajorTask.get(i));
			UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
			userDAO.delete(user);
			UpdateUser();
		}catch(Exception ex){}
	}
	
	public String addNew(User user){
		try{
			UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
			userDAO.save(user);
			UpdateUser();
			return user.getId()+"";
		}catch(Exception ex){}
		return "";
	}
	private static ArrayList<User> removeAdminUser(ArrayList<User> arrUser){
		try{			
			for(int i=0;i < arrUser.size();i++){			
				if(arrUser.get(i).getUserName().equals("admin")){
					arrUser.remove(i);
					return arrUser;
				}
			}
			
		}catch(Exception e){
			
		}
		return arrUser;
	}
	
	private void UpdateUser(){
		try{			
			arrUser = null;
			getAllUser();
			
		}catch(Exception e){
			
		}		
	}
}
